#!/usr/bin/perl -w

##HACKABOT_HELP##
# Create a comic out of the last few lines of conversation. (default: 6 lines)
# !comic [numberoflines]
##HACKABOT_HELP##

use strict;
use DBI;
use Time::localtime;
use URI::Escape;
use XML::Simple;
use LWP::Simple qw($ua get);

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'});
my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};

my $privmsg = 0;
my ($chan, $num, $nick);
while (<>) {
	if (/^type\s+privmsg/) {
		$privmsg = 1;
	}
	elsif (/^to\s+(.+)/) {
		$chan = $1;
	}
	elsif (/^nick\s+(.+)/) {
		$nick = $1;
	}
	elsif (/^msg\s+(\d*)/) {
		$num = $1;
	}
}

if (not defined $nick) {
	die "comic: not all info was given.\n";
}

if (not defined $num or not $num =~ /^\d+$/) {
	$num = 6;
}

if ($privmsg) {
	$chan = undef;
}

my $log = get_log($chan, $num);
$log = uri_escape($log);
$ua->agent("");
$ua->cookie_jar({});
my $page = get("http://chatfu.com/cartoonify?chat=$log");

if ($page =~ m#<B CLASS="share">(\S+)</B>#) {
	print "send $nick: $1\n";
}
elsif ($page =~ m#<DIV ID="instructions" CLASS="round">#) {
	print "send $nick: chatfu.com didn't like the request..."
}
else {
	print "send $nick: chatfu.com didn't return what I wanted..."
}

sub get_log {
	my $chan = shift;
	my $num = shift;
	my ($dbh, $sth);

	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 0 });
	if (!$dbh) {
		die "blame: Failed to connect to database\n";
	}
	
	if (not defined $chan or not $chan =~ m/^#/) {
		$chan = 'NULL';
	}
	else {
		$chan = $dbh->quote($chan);
	}

	$sth = $dbh->prepare("SELECT id,nick,text,type FROM log WHERE chan = $chan ORDER BY id DESC LIMIT $num OFFSET 1");
	$sth->execute;

	my $ret = "";
	my $row;
	while ($row = $sth->fetchrow_hashref) {
		if (not ($row->{'type'} eq "msg" or 
				$row->{'type'} eq "notice" or
				$row->{'type'} eq "action")) {
			next;
		}
		$ret = $row->{'text'}."\n".$ret;
		if ($row->{'type'} eq "action") {
			$ret = "/me ".$ret;
		}
		$ret = $row->{'nick'}.": ".$ret;
	}
	$dbh->disconnect;

	return $ret;
}

